import React, { Component } from 'react';
import { Input, Button, Divider, message, List, Avatar } from 'antd';
import PropTypes from 'prop-types';

import API from '../../../api/files/index';

const { TextArea } = Input;

class TabFileComment extends Component {
  constructor (props) {
    super(props);
    this.state = {
      file: props.file,
      comment: '',
      comments: [],
    };
  }
  getComments = async () => {
    const { id } = this.state.file;
    const response = await API.getComments(id);
    const { code, data } = response;
    if (code === 1) {
      this.setState({
        comments: data,
      });
    }
  }
  addComment = async () => {
    const { comment } = this.state;
    const { id } = this.state.file;
    if (!comment) {
      message.warn('请输入评论');
    } else {
      const params = {
        entity: {
          id,
          type: 'file',
        },
        content: comment,
      };
      const response = await API.addComment(params);
      const { code } = response;
      if (code === 1) {
        this.setState({
          comment: '',
        });
        this.getComments();
      }
    }
  }
  componentDidMount () {
    this.getComments();
  }

    keypress(e) {
        if (e.which == 13){
            e.preventDefault();
            console.log(this);
            this.addComment();
        }
    }


    render () {
    const { comments } = this.state;
    const { style } = this.props; //eslint-disable-line
    return (
      <div style={Object.assign({}, { maxHeight: 600, paddingBottom: 20, overflow: 'auto' }, style)}>
        <List
          style={{ paddingLeft: 20, paddingRight: 20 }}
          itemLayout="horizontal"
          dataSource={comments}
          renderItem={item => (
            // <List.Item actions={[<Icon type="delete" />]}>
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar src={item.author.avatar} />}
                title={item.author.nickname}
                description={
                  <span>
                    <span>{item.content}</span>
                    <br />
                    <sub>{item.createdAt}</sub>
                  </span>
                }
              />
            </List.Item>
          )}
        />
        <Divider />
        <div style={{ margin: '10px 20px' }}>
          <TextArea rows={2} placeholder="请输入评论" value={this.state.comment} onKeyPress={this.keypress.bind(this)}  onChange={(e) => { this.setState({ comment: e.target.value }); }} />
          <Button style={{ marginTop: 10, float: 'right' }} type="primary" onClick={this.addComment}>提交</Button>
        </div>
      </div>
    );
  }
}

TabFileComment.propTypes = {
  file: PropTypes.object.isRequired,
};

export default TabFileComment;
